package com.oop.example.processing.msdoc;

import com.oop.example.processing.Reader;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Реализует алгоритм чтения данных из html документа в котором каждая статья 
 * заключена в тег {@code <p [some atributes]>...</p>}
 * @author -
 */
public class HtmlReader implements Reader {

    private String encoding = "UTF-8";

    @Override
    public String getEncoding() {
        return encoding;
    }

    @Override
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    @Override
    public String[] read(File file) {
        ArrayList<String> out = new ArrayList<String>();
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(file);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in, encoding));
            String strLine;
            String fullLine = "";
            boolean inContext = false;
            while ((strLine = br.readLine()) != null) {

                if (strLine.startsWith("<p")) {
                    fullLine = strLine;
                    inContext = true;//вошли в тег <p>
                    if (strLine.endsWith("</p>")) {
                        //fullLine = cleanLine(fullLine).trim();
                        out.add(fullLine);
                        fullLine = "";
                        inContext = false;//вышли из тега </p>
                    }
                } else if (strLine.endsWith("</p>")) {
                    fullLine += " " + strLine;
                    //fullLine = cleanLine(fullLine).trim();
                    out.add(fullLine);
                    fullLine = "";
                    inContext = false;//вышли из тега </p>
                } else {
                    if (inContext) {
                        fullLine += " " + strLine;
                    }
                }
            }
            in.close();
        } catch (Exception e) {//Catch exception if any
            e.printStackTrace(System.out);
        }
        return out.toArray(new String[]{});
    }
}
